// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/lib/subscript_util.h>

namespace kumo::pollux::functions::sparksql {
    namespace {
        // get(array, index) -> array[index]
        //
        // - allows negative indices for arrays (returns NULL if index < 0).
        // - allows out of bounds accesses for arrays (returns NULL if out of
        //    bounds).
        // - index starts at 0 for arrays.
        class ArrayGetFunction : public SubscriptImpl<
                    /* allowNegativeIndices */ true,
                    /* nullOnNegativeIndices */ true,
                    /* allowOutOfBound */ true,
                    /* indexStartsAtOne */ false> {
        public:
            explicit ArrayGetFunction() : SubscriptImpl(false) {
            }

            static std::vector<std::shared_ptr<exec::FunctionSignature> > signatures() {
                return {
                    // array(T), integer -> T
                    exec::FunctionSignatureBuilder()
                    .typeVariable("T")
                    .returnType("T")
                    .argumentType("array(T)")
                    .argumentType("integer")
                    .build()
                };
            }
        };
    } // namespace

    POLLUX_DECLARE_VECTOR_FUNCTION(
        udf_array_get,
        ArrayGetFunction::signatures(),
        std::make_unique<ArrayGetFunction>());
} // namespace kumo::pollux::functions::sparksql
